import { defineStore } from 'pinia';
import { ref, h, createVNode } from 'vue';
import { notification, Modal} from 'ant-design-vue';
import * as icons from '@ant-design/icons-vue';
import { loginApi, userInfoApi, userMentListApi, outLoginApi, authoritySignApi } from '@/api/user';
import { dictAllApi } from '@/api/sys/dict-type.js';
import route from '@/router/index';
import define from '@/utils/define';
import { useMenu, useTheme } from './index';
import { timeSlotChinese } from '@/utils/tool';


export const useUser = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || null)
  const userInfo = ref(localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {})
  const dictList = ref([])
  const menuList = ref([])
  const authSignList = ref([])

  const login = async (dataForm ) => {
    try {
      const { data:res } = await loginApi(dataForm)
      if (!localStorage.getItem('oaTheme')) {
        localStorage.setItem('oaTheme', 'default')
      }
      localStorage.setItem('token', res.data.token)
      token.value = res.data.token
      await refresh()
      notification.open({
        message: `欢迎访问${define.title}`,
        description: `${timeSlotChinese()}，${userInfo.value.realName || userInfo.value.username}`
      })
      route.replace('/')
      return true
    } catch(err) {
      return false
    }
  }
  const getUserInfo = async () => {
    const { data: res } = await userInfoApi()
    localStorage.setItem('userInfo', JSON.stringify(res.data))
    userInfo.value = res.data
  }
  const getUserMenuList = async () => {
    const { data: res } = await userMentListApi()
    // 组装路由数据 
    function filterMenu(menuList) {
      menuList.forEach(async item => {
        item.key = item.id
        item.label = item.name
        item.title = item.name
        item.path = item.url ? item.url.indexOf('{{ApiUrl}}') === -1 ? `/${item.url}` : `/iframe?href=${encodeURIComponent(item.url.replace(/{{ApiUrl}}/g, import.meta.env.VITE_APP_API))}` : ''
        item.icon = item.icon ?  h(icons[item.icon]) : null
        item.children = item.children.length ? item.children : null
        item.meta = {
          title: item.name
        }
        if (item.children) {
          filterMenu(item.children)
        }
      })
    }
    filterMenu(res.data)
    menuList.value = res.data
    localStorage.setItem('menuList', JSON.stringify(res.data))
  }
  const getAuthSign = async () => {
    const {data:res} = await authoritySignApi()
    authSignList.value = res.data
  }
  const getDictList = async () => {
    const {data:res} = await dictAllApi()
    dictList.value = res.data
  }
  const isRefresh = ref(false)
  const refresh = async () => {
    if (token.value) {
      isRefresh.value = false
      await getAuthSign()
      await getUserInfo()
      await getDictList()
      getUserMenuList()
      isRefresh.value = true
    }
  }

  const outLogin = () => {
    Modal.confirm({
      title: '温馨提示',
      okText: '确认',
      cancelText: '取消',
      icon: createVNode(icons.ExclamationCircleOutlined),
      content: '确定退出登录吗？',
      onOk() {
        useMenu().selectedKeys = []
        return outLoginApi().then(() => {
          clearCache()
          route.replace('/login')
        })
      }
    })
    
  }
  const clearCache = () => {
    localStorage.clear()
    useTheme().mode = 'default'
    token.value = null
    userInfo.value = {}
    menuList.value = []
  }

  return {
    token,
    userInfo,
    menuList,
    dictList,
    authSignList,
    isRefresh,
    login,
    outLogin,
    getUserMenuList,
    getAuthSign,
    getDictList,
    refresh,
    clearCache
  }
})